package com.dong.thread.juc;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * Exchanger 交换器
 * 两个线程互相交换数据用的 只能用于两个线程之间
 *
 * Exchanger.exchange()方法是阻塞方法
 *      也是阻塞子线程，互相等待
 *      两个线程必须都执行了exchange()方法才能继续往下走（有点像CyclicBarrier）
 *
 * @author by jiweidong on 2021/11/28.
 */
public class T08_Exchanger {

    public static void main(String[] args) {

        Exchanger exchanger = new Exchanger();

        new Thread(() -> {
            String s = "T1";
            try {
                TimeUnit.SECONDS.sleep(1);
                s = (String) exchanger.exchange(s);
                System.out.println(Thread.currentThread().getName() + " " + s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            String s = "T2";
            try {
                TimeUnit.SECONDS.sleep(1);
                s = (String) exchanger.exchange(s);
                System.out.println(Thread.currentThread().getName() + " " + s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();


    }

}
